package it.wzm.lightweightlogx;




import it.wzm.lightweightlog.Log;
import it.wzm.lightweightlog.LogFactory;
import it.wzm.lightweightlog.Entry;

import java.util.List;

import javax.ejb.Stateful;
import javax.ejb.Remote;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;



/**
 * Session Bean implementation class LogBean
 */
//@Stateful(mappedName = "ejb/logbean")
//@Stateless(mappedName = "ejb/logbean")
@Stateless
@Remote(LogRemote.class)
//@Interceptors(LogCallbacks.class)
@WebService
public class LogBean implements LogRemote {

	/**
	 *  the persistence unit
	 */
	@PersistenceContext(unitName="lightweightlogPU")
	private EntityManager em;	
	/**
	 * Identify this session...
	 */
	private String personalKey;

	private Log log;
		
    /**
     * Default constructor. 
     */
    public LogBean() {
    }

    /**
     * Initialize the logging...
     */
	@SuppressWarnings("unchecked")
	//@Override
	//@WebMethod
	public boolean init(String personalKey) {
		//System.out.println(personalKey);
		
		// we first look if a client with this key exists...														
		Query q = em.createNamedQuery("Client.findByPersonalKey");
		q.setParameter("personalKey", personalKey);
		List<Client> l = (List<Client>)q.getResultList();
		
		// just a basic check...
		if (l == null || l.isEmpty()) {
			return false;
		} else {
			//System.out.println(l.get(0).getCompany());
			// we found some...
			this.personalKey=l.get(0).getPersonalKey();
			
			// so let's init a database connection
			
			// get our Log...
			log = LogFactory.getLog();
			
			return true;
		}

	}    
	
	//@Override
	public void open() {		
	}
	
	
	public void write() {
		
	}
	
	
	@WebMethod
	public <E extends Entry> void write(String personalkey ,E e) {
	//@Override
	
	//public void write(String personalKey, Object o) { 
		 //Entry e = (Entry)o;
		//System.out.println("writing...");
		// construct XEntry...
		//XEntry x = new XEntry(e.getName(), e.getMessage(), e.getSeverity(), e.getClassname(), e.getTimestamp(), this.personalKey);
		System.out.println("writing: " + personalkey + "::" + e.getMessage());
		// finally add to log...
		//log.add(x);

		/*
Client c = new Client();
c.setClientId(1);
c.setApplicationName("flash");
c.setCompany("Web and Zen Multimedia");
c.setCreated(new java.sql.Timestamp(System.currentTimeMillis()));
c.setEmail("leonardo.celati@poste.it"); 
c.setPersonalKey(String.valueOf(System.currentTimeMillis()));
c.setResponsible("Leonardo Celati, webmaster");
                em.persist(c);       
            */    
		
	}		

    
	//@Override
	//@WebMethod
	public void close() {
		// TODO Auto-generated method stub
		System.out.println("Closing...");
	}




}
